package org.mx.dal.test.service;

import org.mx.dal.test.entity.one.UserEntity;
import org.mx.dal.test.entity.two.UserInfoEntity;
import org.mx.dal.test.repository.one.UserRepository;
import org.mx.dal.test.repository.two.UserInfoRepository;
import org.mx.error.UserInterfaceSystemErrorException;
import org.mx.error.UserInterfaceSystemErrorException.SystemErrors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@SuppressWarnings("javadoc")
@Service
public class UserService {
	@Autowired
	private UserRepository userRepo;

	@Autowired
	private UserInfoRepository userInfoRepo;

	@Transactional(value = "oneTransactionManager", readOnly = false)
	public String saveUser(UserEntity user) {
		UserEntity user1 = userRepo.save(user);
		return user1.toString();
	}
	
	@Transactional(value = "oneTransactionManager", readOnly = false)
	public void clearUser() {
		userRepo.deleteAll();
	}

	@Transactional(value = "oneTransactionManager", readOnly = true)
	public UserEntity getUser(String id) {
		return userRepo.getById(id);
	}

	@Transactional(value = "oneTransactionManager", readOnly = true)
	public long countUser() {
		return userRepo.count();
	}
	
	@Transactional(value = "twoTransactionManager", readOnly = false)
	public void clearUserInfo() {
		userInfoRepo.deleteAll();
	}

	@Transactional(value = "twoTransactionManager", readOnly = false)
	public String saveUserInfo(UserInfoEntity userInfo) {
		UserInfoEntity userInfo1 = userInfoRepo.save(userInfo);
		return userInfo1.toString();
	}

	@Transactional(value = "twoTransactionManager", readOnly = true)
	public UserInfoEntity getUserInfo(String id) {
		return userInfoRepo.getById(id);
	}

	@Transactional(value = "twoTransactionManager", readOnly = true)
	public long countUserInfo() {
		return userInfoRepo.count();
	}

	@Transactional(value = "jtaTransactionManager")
	public void rollback() {
		UserEntity user1 = new UserEntity();
		user1.setId("1");
		user1.setCode("code 1");
		user1.setName("name 1");
		saveUser(user1);

		UserInfoEntity userInfo = new UserInfoEntity();
		userInfo.setId("a");
		userInfo.setDescInfo("Description a");
		saveUserInfo(userInfo);

		throw new UserInterfaceSystemErrorException(SystemErrors.SYSTEM_ILLEGAL_PARAM);
	}
}
